<html>
<head>
    <meta charset="utf-8">
    <title>Кристалловед</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
    <style type="text/css">
        .nlm {
            margin-left:0 !important;
        }
        body {
            margin: 50px 10px;
            padding: 0;
            font-size: 12px
        }
        select, textarea, input[type="text"]{
            font-size: 12px;
        }
        @media (max-width: 979px) {
          body {
            margin: 0;
            padding-top: 0;
          }
        }
    </style>
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <!--link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" /-->
    <script src="js/jquery.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script src="js/json2.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript">


//Порт к которому подключен Arduino
var settings = {
    serialPort: 'COM5',
    weaponTypes:{
         "t_0":"Мечь",
         "t_1":"Топор",
         "t_2":"Пика",
         "t_3":"Алебарда",
         "t_4":"Булава"
    },
    armorTypes:{
         "t_0":"Шлем",
         "t_1":"Корпус",
         "t_2":"Ноги"
    },
    crystallTypes:{
         "t_0":"Универсальный",
         "t_1":"Оружие",
         "t_2":"Доспех"
    },
    types:{
        "t_-1":{
            name: "Не отформаниторан",
            description: "Устройство является новым и не отформатированным ни под один тип",
        },
        "t_0":{
            name: "Отключено",
            description: "Устройство не активно и имеет неизвестный тип",
        },
        "t_1":{
            name: "Кристалл памяти игрока",
            description: "настройки игрока",
            tab: "player_settings",
            img: 'Knight-icon-big.png'
        },
        "t_2":{
            name: "Кристалл памяти оружия",
            description: "настройки оружия",
            tab: "weapon_settings",
            img: 'sword-icon-big.png'
        },
        "t_3":{
            name: "Кристалл памяти доспеха",
            description: "настройки доспеха",
            tab: "armor_settings",
            img: 'shield-icon-big.png'
        },
        "t_4":{
            name: "Простой кристалл улучшения",
            description: "просто память",
            tab: "crystall_settings",
            img: 'ruby-icon-big.png'
        }
    },
    gameSettings:{
        id: 3656,
        groups: {
            "g_1": {
                name: "Человек"
            },
            "g_2": {
                name: "Эльф"
            },
            "g_3": {
                name: "Гном"
            },
            "g_4": {
                name: "Монстр"
            },
            "g_5": {
                name: "Дух"
            }
        },
        outEffects: {
            "e_1":{
                name : "Вспышка"
            }
        },
        inEffects: {
            "e_1":{
                name : "Паралич"
            }
        },
        params:[
            {
                name: "Live", 
                description: "Player live level",
                critical: true,
                min: 0,
                img: 'live.png'
            },
            {
                name: "Manna", 
                description: "Player magic power level",
                critical: false,
                min: 0,
                img: 'mana.png'
            },
            {
                name: "P.Defence", 
                description: "Phusical defence",
                critical: false,
                min: 0,
                img: 'shield-icon.png'
            },
            {
                name: "P.Atac", 
                description: "Phusical atac",
                critical: false,
                min: 0,
                img: 'sword-icon.png'
            },
            {
                name: "M.Defence", 
                description: "Magic defence",
                critical: false,
                min: 0,
                img: 'm_shield-icon.png'
            },
            {
                name: "M.Atac", 
                description: "Magic atac",
                critical: false,
                min: 0,
                img: 'wizard-icon.png'
            },
            {
                name: "M.Speed", 
                description: "Magic Speed",
                critical: false,
                min: 0,
                img: 'wizard-speed-icon.png'
            }
        ]
    }
}
//непосредственно управляющая функция
var Arduino = function(mode, start, read, data,callback){
    var mode = mode;
    var read = read;
    var callback = callback;
    var command = mode+(start*1 || 0)+"("+(read*1 || 1)+")["+(data? (typeof data == "object" ? data.join('_') : data+"|") : "")+"]";
    $.get('c.py',{
        c:command,
        p:settings.serialPort
    }, function(data){
        data = $.trim(data);
        console.log(data);
        if(typeof callback == 'function'){
            if(mode == "r" || mode == "w"){
                data = read>1 || mode == "w" ? data.split("|") : [data];
                for(var i in data){
                    data[i] = data[i]*1
                }
            }
            callback(data);
        }
    });
}

//Отображение контролов
var Controller = function(){
    this.updated = true;
    this.ports = 13;
    this.currentTab = 'settings';
    this.container = $('#list');
    this.player_settings = new player_settings_class();
    this.weapon_settings = new weapon_settings_class();
    this.armor_settings = new armor_settings_class();
    this.crystall_settings = new crystall_settings_class();
    this.lib_settings = new lib_settings_class();
    this.init_crystall = new init_crystall_class();
    this.settings = new settings_class();
    this.pushList = [];
    this.start = function(){
        var self = this;
        $(".arduinoAction").on('click', function(){
            self[$(this).data("function")]();
        });
        var data = window.localStorage['lib'];
        if(!data) return;
        this.lib_settings.data.params = $.parseJSON(data);
    }
    this.initData = function(){
        var that = this;
        $('#initResult').html('Загрузка...');
        Arduino("r",0,2,false,function(data){
            console.log(data);
            var type = settings.types['t_'+data[1]];
            if(undefined == type) {
                type = settings.types['t_-1'];
                var name = type.name+" "+data[1];
            }else{
                var name = type.name;
            }
            $('#initResult').html('<br/><div class="span12" id="crystallInfoBlock"><div><b>ID</b>: '+data[0]+'</div>\
                <div><b>Тип</b>: '+name+'</div>\
                <div><b>Описание</b>: '+type.description+'</div></div><br/>');
            if(data[1] <1) return;
            $('#initResult').append($('<button>')
                .attr('class', "btn arduinoAction")
                .text('Использовать')
                .click(function(){ 
                    that.useChip(data)
                })
            );
            switch(data[1]){
                case 1:{
                    Arduino("p",50,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",4,2,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>ID</b>: '+data[0]+'</div>\
                                <div><b>ID группы</b>: '+data[1]+'</div>');
                            
                        });
                    });
                    
                }break;
                case 2:{
                    Arduino("p",20,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",6,1,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>Тип</b>: '+settings.weaponTypes['t_'+data[0]]+'</div>');
                        });
                    });
                    
                }break;
                case 4:{
                    Arduino("p",20,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",6,1,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>Тип</b>: '+settings.crystallTypes['t_'+data[0]]+'</div>');
                        });
                    });
                    
                }break;
            }
        });
    }
    this.useChip = function(data){
        console.log('UseChip function', data);
        this.updated = false;
        $('#baseMenu a[href="#'+settings.types['t_'+data[1]].tab+'"]').tab('show');
        this.load();
    }
    this.load = function(){
        controller[controller.currentTab].load();
    }
    this.save = function(){
        controller[controller.currentTab].save();
    }
    this.clean = function(){
        controller[controller.currentTab].clean();
    }
    this.reset = function(){
        
    }
    this.pushData = function(data, callback){
        controller.pushList = data;
        var saveElement = function(element,callback){
            Arduino(element[0],element[1],element[2],element[3],function(data){
                if(controller.pushList.length){
                    setTimeout(function(){
                        saveElement(controller.pushList.shift(),callback);
                    }, 100);
                }else if(typeof callback == 'function') callback();
            });
        }
        saveElement(controller.pushList.shift(),callback);
    }
    this.showAlert = function(text){
        $('#alertText').html(text);
        $('#topAlert').show();
        setTimeout(function(){
            $('#topAlert').hide();
        },3000);
    }
    this.buildElementSelect = function(i, data, useproc){
        useproc = useproc || false;
        var elementSelect = $("<select>").attr('class','span12')
            .attr('data-num',i)
            .attr('data-param','element')
            .change(function(){
                data.params[$(this).data('num')].element = $(this).val().split('_')[0]*1;
                data.params[$(this).data('num')].param = 10*($(this).val().split('_')[1]*1+1) + $(this).val().split('_')[2]*1;
            })
        for(var m = 0; m<settings.gameSettings.params.length; m++){
            elementSelect.append('<optgroup label="'+settings.gameSettings.params[m].name+'">');
            elementSelect.append('<option value="'+m+'_0_0">'+settings.gameSettings.params[m].name+'</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_0_1">'+settings.gameSettings.params[m].name+' %</option>');
            elementSelect.append('<option value="'+m+'_1_0">'+settings.gameSettings.params[m].name+' (max)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_1_1">'+settings.gameSettings.params[m].name+' (max) %</option>');
            elementSelect.append('<option value="'+m+'_2_0">'+settings.gameSettings.params[m].name+' (рост)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_2_1">'+settings.gameSettings.params[m].name+' (рост) %</option>');
            elementSelect.append('<option value="'+m+'_3_0">'+settings.gameSettings.params[m].name+' (коэф.)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_3_1">'+settings.gameSettings.params[m].name+' (коэф.) %</option>');
            elementSelect.append('<option value="'+m+'_4_0">'+settings.gameSettings.params[m].name+' (стойкость коэф.)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_4_1">'+settings.gameSettings.params[m].name+' (стойкость коэф.) %</option>');
            elementSelect.append('<option value="'+m+'_5_0">'+settings.gameSettings.params[m].name+' (ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_5_1">'+settings.gameSettings.params[m].name+' (ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_6_0">'+settings.gameSettings.params[m].name+' (max ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_6_1">'+settings.gameSettings.params[m].name+' (max ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_7_0">'+settings.gameSettings.params[m].name+' (рост ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_7_1">'+settings.gameSettings.params[m].name+' (рост ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_8_0">'+settings.gameSettings.params[m].name+' (коэф. ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_8_1">'+settings.gameSettings.params[m].name+' (коэф. ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_9_0">'+settings.gameSettings.params[m].name+' (стойкость коэф. ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_9_1">'+settings.gameSettings.params[m].name+' (стойкость коэф. ВРЕМЕННО) %</option>');
            elementSelect.append('</optgroup><optgroup></optgroup>');
        }
        return elementSelect;
    }
    this.showLib = function(type){
        this.updateLib(type);
        $("#libModal").modal('show');
    }
    this.hideLib = function(){
        $("#libModal").modal('hide');
    }
    this.updateLib = function(type){
        $('#libList li').remove();
        var self = this;
        var ul = $('#libList');
        $(this.lib_settings.data.params).each(function(){
            if(!this.id) return;
            if(undefined != type && this.type > 0 && this.type != type) return;
            var li = $('<li></li>').height(30);
            li.append($('<div class="span1 nlm"><label class="checkbox"><input type="checkbox" value="'+this.id+'"/>'+this.id+'</label></div>'));
            li.append($('<div class="span8" style="position:relative"></div>').append(self.getInfoLine(this, false)));
            ul.append(li);
        });
    }
    this.getInfoLine = function(data, editable, weaponMode){
        if(!data || data == -1) return "";
        var span = $('<span></span>');
        span.append($('<img>').attr('src',"img/"+['ruby-icon.png','sword-icon.png','shield-icon.png'][data.type]).attr('title',settings.crystallTypes['t_'+[data.type]]));
        if(data.groupId > 0 ){
            span.append($('<span style="padding:0 10px"><img src="img/Knight-icon.png"/> ('+data.groupId+' '+settings.gameSettings.groups['g_'+data.groupId].name+')</span>'));
        }else{
            span.append($('<span style="padding:0 17px">всем</span>'));
        }
        if(undefined != weaponMode){
            var typeSelect = $("<select>").attr('class','span2').attr('name','weaponType_'+data.id).css({
                'marginRight':10,
                'marginBottom':0
            });
            typeSelect.append('<option value="0">0 На врага</option>');
            typeSelect.append('<option value="1">1 На себя постоянно</option>');
            typeSelect.append('<option value="2">2 На себя при ударе</option>');
            typeSelect.append('<option value="3">3 На себя при убийстве</option>');
            span.append(typeSelect.val(weaponMode));
        }
        span.append($('<img>').attr('src',"img/"+settings.gameSettings.params[data.element].img).css('margin-right',10).attr('title',settings.gameSettings.params[data.element].name));
        var p = data.param ? parseInt(data.param/10)-1 : 0;
        var t = data.param ? data.param - parseInt(data.param/10)*10 : 0;
        var text = p < 5 ? "<img src='img/time-icon.png' title='ежесекундно'/> " : "";
        if(p == 1 || p == 6) text += " максимальное ";
        else if(p == 2 || p == 7) text += " прирост "
        else if(p == 3 || p == 8) text += " коэффициент "
        else if(p == 4 || p == 9) text += " стойкость "
        if(editable){
            text += "<a href='javascript:void(0)' onclick='controller.changeValueStart(this)'>"+data.value+"</a><input type='hidden' name='chValue_"+data.id+"' value='"+data.ch+"'/><input type='text' class='span2' name='value_"+data.id+"' value='"+data.value+"' onchange='controller.changeValueEnd(this)' style='margin-bottom: 0;width: 50px;display:none'/>";
        } else  {
            text += "<span style='color:"+(data.value > 0 ? "red":"green")+ "'>"+Math.abs(data.value)+'</span>';
        }
        text += t ? "%" : "";
        span.append($('<span>'+text+'</span>'));
        if(data.defender > 0 ){
            span.append($('<span style="padding:0 10px">><img src="img/'+settings.gameSettings.params[data.defender].img+'" title="'+settings.gameSettings.params[data.defender].name+'"/><</span>'));
        }
        if(data.range > 0){
            if(data.range<100){
                span.append($('<span style="margin-left:20px">'+data.range+' м.</span>'));       
            }else if(data.range < 1000){
                span.append($('<span style="margin-left:20px">'+(data.range - Math.floor(data.range/100)*100)+' м. -'+(Math.floor(data.range/100)*10)+'% за 1м. сверх</span>'));
            }else{
                var c1 = Math.floor(data.range / 1000);
                var c2 = Math.floor((data.range - c1*1000) / 100);
                span.append($('<span style="margin-left:20px"> '+(data.range -c1*1000 - c2*100)+' м. +'+c1+'цепей на '+c2+'м.</span>'));
            }
        }
        if(data.outEffect > 0){
            span.append($('<span style="margin-left:20px" title="Эффект кастующего">< '+settings.gameSettings.outEffects['e_'+data.outEffect].name+' ></span>'));
        }
        if(data.inEffect > 0){
            span.append($('<span style="margin-left:20px" title="Эффект на цели">> '+settings.gameSettings.inEffects['e_'+data.inEffect].name+' <</span>'));
        }
        var rightDiv = $("<div></div>").css({
            position: "absolute",
            right: 0,
            top: 2
        });
        if(data.manna > 0 ){
            rightDiv.append($('<span style="margin-right:20px"><img src="img/mana.png"/> '+data.manna+'</span>'));
        }
        if(data.maxCount > 0 ){
            rightDiv.append($('<span>('+(editable ? " <input type='text' class='span2' style='margin-bottom: 0;width: 50px;' name='count_"+data.id+"' value='"+data.count+"'/> из " : "")+data.maxCount+')</span>'));
        }
        
        span.append(rightDiv);
        return span;
    }
    this.addLinesFromLib = function(){
        $('#libList li input[type=checkbox]:checked').each(function(){
            controller[controller.currentTab].createLine(this.value*1);
        });
        this.hideLib();
    }
    this.libEl = function(id){
        if(id<10000)id+=10000;
        for(var i=0; i<this.lib_settings.data.params.length; i++){
            if(this.lib_settings.data.params[i].id == id*1) return this.lib_settings.data.params[i];
        }
        return -1;
    }
    this.buildSelectGroup = function(groupId, name, className){
        var select = $('<select></select>').attr('name',name).attr('class', className || 'span2').css({'marginBottom':0});
        select.append($('<option value="0">0 Все</option>'))
        for(var k in settings.gameSettings.groups){
            select.append($('<option value="'+k.split('_')[1]+'">'+k.split('_')[1]+" "+settings.gameSettings.groups[k].name+'</option>'));
        };
        for(var k in settings.gameSettings.groups){
            select.append($('<option value="-'+k.split('_')[1]+'">-'+k.split('_')[1]+" не "+settings.gameSettings.groups[k].name+'</option>'));
        };
        select.val(groupId);
        return $('<span></span>').append(select);
    }
    this.start();
    this.changeValueStart = function(element){
        $(element).hide().parent().find("input[type=text]:first").show();
    }
    this.changeValueEnd = function(element){
        $(element).hide().parent().find("a:first").html(element.value).show();
        $(element).parent().find("input[type=hidden]").val(1);
    }
}

//////////////////////////////////////////////////////////////////////////////

var init_crystall_class = function(){
    this.show = function(){

    }
    this.save = function(){
        
    }
    this.load = function(){
        
    }
    this.clean = function(){
        
    }
}

var settings_class = function(){
    this.show = function(){
        $('#comport_name').val(settings.serialPort);
        $('#gameSettings').html('').append("<legend>ID игры</legend><br/>");
        $('#gameSettings').append($("<div></div>").attr('class','span11').append(
            $("<input>").attr("type","text")
                .attr('class','span2')
                .val(settings.gameSettings.id)
                .change(function(){
                    settings.gameSettings.id = this.value
                })
            )
        );
        $('#gameSettings').append("<legend>Параметры игры</legend><div class='span11'><div style='float:left'>#</div><div class='span2'>Название (10 букв)</div><div class='span5'>Описание (70 букв)</div><div class='span2'>Минимальное</div><div class='span2'>Жизненно важно</div></div>");
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            var div = $("<div class='span11'></div>");
            div.append($("<div>"+i+"</div>").css('float','left'));
            div.append($("<div><img src='img/"+settings.gameSettings.params[i].img+"' style='margin-right:10px'/></div>").css("whiteSpace","nowrap")
                .attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span8')
                        .attr('data-num',i)
                        .val(settings.gameSettings.params[i].name)
                        .change(function(){
                            this.value = this.value.substr(0,10);
                            settings.gameSettings.params[$(this).data('num')].name = this.value;
                        })
                    )
                );
            div.append($("<div></div>").attr('class','span5').append(
                $("<input>").attr("type","text")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .val(settings.gameSettings.params[i].description)
                    .change(function(){
                        this.value = this.value.substr(0,70);
                        settings.gameSettings.params[$(this).data('num')].description = this.value;
                    })
                )
            );
            div.append($("<div></div>").attr('class','span2').append(
                $("<input>").attr("type","text")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .val(settings.gameSettings.params[i].min)
                    .change(function(){
                        this.value = parseInt(this.value) || 0;
                        settings.gameSettings.params[$(this).data('num')].min = this.value;
                    })
                )
            );
            div.append($("<div></div>").attr('class','span2').append(
                $("<input>").attr("type","checkbox")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .attr('checked',settings.gameSettings.params[i].critical)
                    .change(function(){
                        settings.gameSettings.params[$(this).data('num')].critical = this.checked;
                    })
                )
            );
            $('#gameSettings').append(div);
        }

        $('#gameSettings').append("<legend>Еффекты мага</legend><div class='span11'><div style='float:left'>#</div><div class='span2'>Название</div></div>");
        for(var i  in settings.gameSettings.outEffects){
            var div = $("<div class='span11'></div>");
            div.append($("<div>"+i.split('_')[1]+"</div>").css('float','left'));
            div.append($("<div></div>").css("whiteSpace","nowrap")
                .attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span8')
                        .attr('data-num',i)
                        .val(settings.gameSettings.outEffects[i].name)
                        .change(function(){
                            this.value = this.value.substr(0,10);
                            settings.gameSettings.outEffects[$(this).data('num')].name = this.value;
                        })
                    )
                );
            $('#gameSettings').append(div);
        }
        $('#gameSettings').append("<legend>Еффекты цели</legend><div class='span11'><div style='float:left'>#</div><div class='span2'>Название</div></div>");
        for(var i  in settings.gameSettings.inEffects){
            var div = $("<div class='span11'></div>");
            div.append($("<div>"+i.split('_')[1]+"</div>").css('float','left'));
            div.append($("<div></div>").css("whiteSpace","nowrap")
                .attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span8')
                        .attr('data-num',i)
                        .val(settings.gameSettings.inEffects[i].name)
                        .change(function(){
                            this.value = this.value.substr(0,10);
                            settings.gameSettings.inEffects[$(this).data('num')].name = this.value;
                        })
                    )
                );
            $('#gameSettings').append(div);
        }
    }
    this.save = function(){
        
    }
    this.load = function(){
        
    }
    this.clean = function(){
        
    }
}

var player_settings_class = function(){
    this.data = {
        selfId: 0,
        userId: 0,
        groupId: 0,
        name: "",
        params:[]
    };
    this.changeParam = function(el){
        var num = el.data('num');
        if(undefined == this.data.params[num]) this.data.params[num] = {
            current: 0,
            max: 0,
            inc: 0,
            koef: 100,
            strong: 0
        };
        this.data.params[num][el.data('param')] = el.val()*1;
    }
    this.show = function(){
        var that = this;
        $('#player_settings form [name=self_id]').val(this.data.selfId);
        $('#player_settings form [name=user_id]').val(this.data.userId);
        $('#player_settings form [name=group_id]').val(this.data.groupId);
        $('#playerGroupIdControll').html('').append(
            controller.buildSelectGroup(this.data.groupId,'group_id','span12').find('select')
                .change(function(){
                    that.data.groupId = $(this).val();
                })
        );
        $('#player_settings form [name=user_name]').val(this.data.name);
        $("#user_params_value").html("<span class='span2 hide'></span>");
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            var div = $("<div class='span11'></div>").append("<span class='span2' style='white-space:nowrap'><img src='img/"+settings.gameSettings.params[i].img+"' style='margin-right:10px'/><b title='"+settings.gameSettings.params[i].description+"'>"+settings.gameSettings.params[i].name+"</b></span>");
            div.find('b').tooltip();
            $(['current','max','inc','koef','strong']).each(function(){
                div.append($("<div></div>").attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span12')
                        .attr('data-num',i)
                        .attr('data-param',this)
                        .val(that.data.params[i] ? that.data.params[i][this] : (this == 'koef' ? 100 : 0))
                        .change(function(){
                            that.changeParam($(this));
                        })
                    )
                );
            });
            $("#user_params_value").append(div);
        }
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<controller.lib_settings.data.params.length; i++){
            if(controller.lib_settings.data.params[i] !== false) tmp.push(controller.lib_settings.data.params[i]);
        }
        console.log(tmp);
        var that = this;
        var data = [
            ["w",0,0,[this.data.selfId,1,this.data.userId,this.data.groupId]],
            ["s",50,50,that.data.name],
            ["w",1000,2,[settings.gameSettings.id, settings.gameSettings.params.length]]
        ];
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            if(undefined == this.data.params[i]) this.data.params[i] = {
                current: 0,
                max: 0,
                inc: 0,
                koef: 100,
                strong: 0
            };
            data.push(["w",100+10*i,    0,  [this.data.params[i].current, this.data.params[i].max, this.data.params[i].inc, this.data.params[i].koef, this.data.params[i].strong]]);
            data.push(["s",1100+100*i, 10, settings.gameSettings.params[i].name]);
            //data.push(["s",1110+100*i,   70, settings.gameSettings.params[i].description]);
            data.push(["w",1180+100*i, 2,  [settings.gameSettings.params[i].critical ? 1 : 0 , settings.gameSettings.params[i].min]]);
        }
        //записываем библиотеку
        for(var i = 0; i<tmp.length; i++){
            tmp[i].id = tmp[i].id < 10000 ? 10000+tmp[i].id*1 : tmp[i].id*1;    //проверка чоб id не  был меньше 10000
            var id = (tmp[i].id -10000)*100+10000;
            data.push(["w",id, 0, [
                tmp[i].id,
                tmp[i].type,
                tmp[i].groupId,
                tmp[i].element,
                tmp[i].param || 10,
                tmp[i].value,
                tmp[i].defender,
                tmp[i].manna,
                tmp[i].count,
                tmp[i].maxCount,
                tmp[i].range,
                tmp[i].outEffect,
                tmp[i].inEffect
            ]]);
        }
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
        Arduino("r",0,4,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.userId = data[2]*1;
            that.data.groupId = data[3]*1;
            Arduino("p",50,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,settings.gameSettings.params.length*5,false,function(data){
                    for(var i = 0; i<settings.gameSettings.params.length; i++){
                        that.data.params[i] = {
                            current: data[i*5],
                            max: data[i*5+1],
                            inc: data[i*5+2],
                            koef: data[i*5+3],
                            strong: data[i*5+4]
                        };
                    }
                    that.show();
                });
            });
        });
        
    }
    this.clean = function(){
        
    }
}

var weapon_settings_class = function(){
    this.data = {
        selfId: 0,
        gameId: 0,
        type: 0,
        name: "",
        delay: 300,
        level: 300,
        owner: 0,
        damage: 0,
        params:[]
    };
    this.showMode = false;
    this.show = function(){
        var that = this;
        $('#weapon_settings form [name=self_id]').val(this.data.selfId);
        $('#weapon_settings form [name=game_id]').val(this.data.gameId);
        $('#weapon_settings form [name=type]').val(this.data.type);
        $('#weapon_settings form [name=weapon_name]').val(this.data.name);
        $('#weapon_settings form [name=delay]').val(this.data.delay);
        $('#weapon_settings form [name=level]').val(this.data.level);
        $('#weapon_settings form [name=owner]').val(this.data.owner);
        $('#weapon_settings form [name=damage]').val(this.data.damage);
        $("#weapon_value").html("");
        for(var i in settings.weaponTypes) {
            $('#weapon_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.weaponTypes[i]));
        }
        this.showMode = true;
        for(var i = 0; i<this.data.params.length; i++){
            this.createLine(this.data.params[i]);
        }
        this.showMode = false;
    }
    this.createLine = function(i, value, count, type){
        var el = controller.libEl(i);
        if(!el || el == -1) return;
        if(undefined != value) el.value = value;
        if(undefined != value) el.count = count;
        if(this.data.params.indexOf(el.id) > -1 && !this.showMode) return;
        else if(!this.showMode) this.data.params.push(el.id);
        var that = this;
        var div = $("<div>"+el.id+" </div>")
            .attr('class','span12 nlm')
            .css({
                'position': 'relative',
                'height': 40
            });
        div.append(controller.getInfoLine(el, true, type||0));
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","button")
                .attr('class','btn btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    delete(that.data.params[that.data.params.indexOf($(this).data('num')*1)]);
                    $(this).parent().parent().remove();
                })
            )
        );
        $("#weapon_value").append(div);
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<this.data.params.length; i++){
            if(this.data.params[i] != false) tmp.push(this.data.params[i]);
        }
        var that = this;
        var data = [
            ["w",0,0,[
                this.data.selfId, 
                2, 
                this.data.gameId || settings.gameSettings.id,
                this.data.type,
                tmp.length,
                this.data.level,
                this.data.delay,
                this.data.owner,
                this.data.damage
            ]],
            ["s",20,50,that.data.name]
        ];
        for(var i = 0; i<tmp.length; i++){
            var val = $('#weapon_settings input[name=chValue_'+tmp[i]+']').val()==1 ? $('#weapon_settings input[name=value_'+tmp[i]+']').val()*1 : 0;
            data.push(["w",100+10*i, 0, [tmp[i], val, $('#weapon_settings input[name=count_'+tmp[i]+']').val()*1 || 0, $('#weapon_settings select[name=weaponType_'+tmp[i]+']').val()*1,0]]);
        }
        console.log(data);
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
        this.clean();
        Arduino("r",0,9,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.gameId = data[2]*1;
            that.data.type = data[3]*1;
            var paramlength = data[4]*1;
            that.data.level = data[5]*1; 
            that.data.delay = data[6]*1; 
            that.data.owner = data[7]*1;
            that.data.damage = data[8]*1;
            Arduino("p",20,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,5*paramlength,false,function(data){
                    that.data.params = [];
                    for(var i = 0; i<paramlength; i++){
                        that.data.params.push(data[i*5]);
                        that.createLine(i, data[i*5]+1, data[i*5]+2, data[i*5]+3);
                    }
                    that.show();
                });
            });
        });
    }
    this.clean = function(){
        $("#weapon_value>div").remove();
        this.data.params = [];
    }
    var that = this;
        $('#addWeaponLine').click(function(){
        controller.showLib(1);
    });
}

var armor_settings_class = function(){
    this.data = {
        selfId: 0,
        gameId: 0,
        type: 0,
        name: "",
        owner: 0,
        defend: 0,
        params:[]
    };
    this.showMode = false;
    this.show = function(){
        var that = this;
        $('#armor_settings form [name=self_id]').val(this.data.selfId);
        $('#armor_settings form [name=game_id]').val(this.data.gameId);
        $('#armor_settings form [name=type]').val(this.data.type);
        $('#armor_settings form [name=armor_name]').val(this.data.name);
        $('#armor_settings form [name=owner]').val(this.data.owner);
        $('#armor_settings form [name=defende]').val(this.data.defende);
        $("#armor_value").html("");
        for(var i in settings.armorTypes) {
            $('#armor_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.armorTypes[i]));
        }
        this.showMode = true;
        for(var i = 0; i<this.data.params.length; i++){
            this.createLine(this.data.params[i]);
        }
        this.showMode = false;
    }
    this.createLine = function(i, value, count, type){
        var el = controller.libEl(i);
        if(!el || el == -1) return;
        if(undefined != value) el.value = value;
        if(undefined != value) el.count = count;
        if(this.data.params.indexOf(el.id) > -1 && !this.showMode) return;
        else if(!this.showMode) this.data.params.push(el.id);
        var that = this;
        var div = $("<div>"+el.id+" </div>")
            .attr('class','span12 nlm')
            .css({
                'position': 'relative',
                'height': 40
            });
        div.append(controller.getInfoLine(el, true));
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","button")
                .attr('class','btn btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    delete(that.data.params[that.data.params.indexOf($(this).data('num')*1)]);
                    $(this).parent().parent().remove();
                })
            )
        );
        $("#armor_value").append(div);
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<this.data.params.length; i++){
            if(this.data.params[i] != false) tmp.push(this.data.params[i]);
        }
        var that = this;
        var data = [
            ["w",0,0,[
                this.data.selfId, 
                2, 
                this.data.gameId || settings.gameSettings.id,
                this.data.type,
                tmp.length,
                this.data.owner,
                this.data.defende
            ]],
            ["s",20,50,that.data.name]
        ];
        for(var i = 0; i<tmp.length; i++){
            var val = $('#armor_settings input[name=chValue_'+tmp[i]+']').val()==1 ? $('#armor_settings input[name=value_'+tmp[i]+']').val()*1 : 0;
            data.push(["w",100+10*i, 0, [tmp[i], val, $('#armor_settings input[name=count_'+tmp[i]+']').val()*1 || 0, $('#armor_settings select[name=armorType_'+tmp[i]+']').val()*1,0]]);
        }
        console.log(data);
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
        this.clean();
        Arduino("r",0,9,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.gameId = data[2]*1;
            that.data.type = data[3]*1;
            var paramlength = data[4]*1;
            that.data.owner = data[5]*1;
            that.data.defende = data[6]*1;
            Arduino("p",20,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,5*paramlength,false,function(data){
                    that.data.params = [];
                    for(var i = 0; i<paramlength; i++){
                        that.data.params.push(data[i*5]);
                        that.createLine(i, data[i*5]+1, data[i*5]+2, data[i*5]+3);
                    }
                    that.show();
                });
            });
        });
    }
    this.clean = function(){
        $("#armor_value>div").remove();
        this.data.params = [];
    }
    var that = this;
        $('#addArmorLine').click(function(){
        controller.showLib(2);
    });
}

var crystall_settings_class = function(){
    this.data = {
        selfId: 0,
        gameId: 0,
        type: 0,
        name: "",
        params:[],
        values:[]
    };
    this.showMode = false;
    this.show = function(){
        var that = this;
        $('#crystall_settings form [name=self_id]').val(this.data.selfId);
        $('#crystall_settings form [name=game_id]').val(this.data.gameId);
        $('#crystall_settings form [name=crystall_name]').val(this.data.name);
        $("#crystall_value").html("");
        $('#crystall_settings form [name=type]').html("");
        for(var i in settings.crystallTypes) {
            $('#crystall_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.crystallTypes[i]));
        }
        $('#crystall_settings form [name=type]').val(this.data.type);
        this.showMode = true;
        for(var i = 0; i<this.data.params.length; i++){
            if(undefined != this.data.values[this.data.params[i]]){
                this.createLine(this.data.params[i],this.data.values[this.data.params[i]][0],this.data.values[this.data.params[i]][1]);
            }else{
                this.createLine(this.data.params[i]);
            }
        }
        this.showMode = false;
    }
    this.createLine = function(i, value, count){
        //var data = this.data.params[i]
        var el = controller.libEl(i);
        if(!el || el == -1) return;
        el['ch'] = 0;
        if(undefined != value) {
            if(value*1 != 0){
                el.value = value;
                el['ch'] = 1;
            }
        }
        if(undefined != count) el.count = count;
        if(this.data.params.indexOf(el.id) > -1 && !this.showMode) return;
        else if(!this.showMode) {
            this.data.params.push(el.id);
            this.data.values[el.id] = [0,0];
        }
        var that = this;
        var div = $("<div>"+el.id+" </div>")
            .attr('class','span12 nlm')
            .css({
                'position': 'relative',
                'height': 40
            });
        div.append(controller.getInfoLine(el,true));
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","button")
                .attr('class','btn btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    delete(that.data.values[$(this).data('num')*1]);
                    delete(that.data.params[that.data.params.indexOf($(this).data('num')*1)]);
                    $(this).parent().parent().remove();
                })
            )
        );
        $("#crystall_value").append(div);
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<this.data.params.length; i++){
            if(this.data.params[i] != undefined) tmp.push(this.data.params[i]);
        }
        var that = this;
        var data = [
            ["w",0,0,[
                this.data.selfId, 
                4, 
                this.data.gameId || settings.gameSettings.id,
                this.data.type,
                tmp.length
            ]],
            ["s",20,50,that.data.name]
        ];
        for(var i = 0; i<tmp.length; i++){
            var val = $('#crystall_settings input[name=chValue_'+tmp[i]+']').val()==1 ? $('#crystall_settings input[name=value_'+tmp[i]+']').val()*1 : 0;
            this.data.values[tmp[i]] = [val, $('#crystall_settings input[name=count_'+tmp[i]+']').val()*1 || 0];
            data.push(["w",100+10*i, 0, [tmp[i],  this.data.values[tmp[i]][0],  this.data.values[tmp[i]][1], 0,0]]);
        }
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
        this.clean();
        Arduino("r",0,5,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.gameId = data[2]*1;
            that.data.type = data[3]*1;
            var paramlength = data[4]*1;
            Arduino("p",20,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,5*paramlength,false,function(data){
                    that.data.params = [];
                    for(var i = 0; i<paramlength; i++){
                        that.data.values[data[i*5]] = [data[i*5+1], data[i*5+2]];
                        that.data.params.push(data[i*5]);
                    }
                    that.show();
                });
            });
        });
    }
    this.clean = function(){
        $("#crystall_value>div").remove();
        this.data.params = [];
    }
    var that = this;
    $('#addCrystallLine').click(function(){
        controller.showLib();
    });
}
var lib_settings_class = function(){
    this.data = {
        params:[]
    };
    this.changeParam = function(el){
        var num = el.data('num');
        this.data.params[num][el.data('param')] = el.val()*1;
    }
    this.changeRange = function(el){
        var num = el.data('num');
        var dist =  el.parent().find('[data-param=rangeDistance]').val();
        this.data.params[num]['range'] = parseInt(el.parent().find('[data-param=rangeSelect]').val() + '' + (dist < 10 ? '0'+dist : dist));
    }
    this.show = function(){
        var that = this;
        $('#lib_settings form [name=self_id]').val(this.data.selfId);
        $('#lib_settings form [name=game_id]').val(this.data.gameId);
        $('#lib_settings form [name=lib_name]').val(this.data.name);
        $("#lib_value").html("");
        $('#lib_settings form [name=type]').html("");
        for(var i in settings.libTypes) {
            $('#lib_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.libTypes[i]));
        }
        $('#lib_settings form [name=type]').val(this.data.type);
        for(var i = 0; i<this.data.params.length; i++){
            if(!this.data.params[i]) continue; 
            this.createLine(i);
        }
        $('#saveToLS').click(function(){
            that.saveToLS();
        })
        $('#loadFromLS').click(function(){
            that.loadFromLS();
        })
    }
    this.createLine = function(i){
        var data = this.data.params[i]
        var that = this;
        var div = $("<div></div>")
            .attr('class','span12')
            .css('marginLeft', 0);
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","text")
                .attr('class','btn-mini')
                .css('width',"100%")
                .attr('data-num',i)
                .attr('data-param','id')
                .val(data.id)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var typeSelect = $("<select>").attr('class','btn-mini')
            .css({
                width: '100%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','type')
            .change(function(){
                that.changeParam($(this));
            });
        for(var m = 1 in settings.crystallTypes){
            typeSelect.append('<option value="'+m.split('_')[1]+'">'+m.split('_')[1]+' '+settings.crystallTypes[m]+'</option>');
        }
        div.append($("<div></div>").attr('class','span1 nlm').append(typeSelect.val(data.type)));
        div.append($("<div></div>").attr('class','span1 nlm').append(
            controller.buildSelectGroup(data.groupId,'group', 'btn-mini').find('select')
                .css({
                    width: '100%',
                    height: "auto"
                })
                .attr('data-num',i)
                .attr('data-param','groupId')
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var sel = controller.buildElementSelect(i, that.data, true);
        sel.attr('class','btn-mini')
            .css({
                width: '100%',
                height: "auto"
            });
        div.append($("<div></div>").attr('class','span2 nlm').append(sel));
        var p = [parseInt(data.param/10)-1,data.param - parseInt(data.param/10)*10];
        sel.val(data.element+"_"+p[0]+"_"+p[1]);
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","text")
                .attr('class','btn-mini')
                .css('width',"100%")
                .attr('data-num',i)
                .attr('data-param','value')
                .val(data.value)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var defenderSelect = $("<select>").attr('class','btn-mini')
            .css({
                width: '100%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','defender')
            .change(function(){
                that.changeParam($(this));
            });
        defenderSelect.append('<option value="0">--</option>');
        for(var m = 1; m<settings.gameSettings.params.length; m++){
            defenderSelect.append('<option value="'+m+'">'+settings.gameSettings.params[m].name+'</option>');
        }
        div.append($("<div></div>").attr('class','span1 nlm').append(defenderSelect.val(data.defender)));
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","text")
                .attr('class','btn-mini')
                .css('width',"100%")
                .attr('data-num',i)
                .attr('data-param','manna')
                .val(data.manna)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","text")
                .attr('class','btn-mini')
                .css('width',"100%")
                .attr('data-num',i)
                .attr('data-param','count')
                .val(data.count)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1 nlm').append(
            $("<input>").attr("type","text")
                .attr('class','btn-mini')
                .css('width',"100%")
                .attr('data-num',i)
                .attr('data-param','maxCount')
                .val(data.maxCount)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var rangeDistance = $("<select>").attr('class','btn-mini')
            .css({
                width: '30%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','rangeDistance')
            .change(function(){
                that.changeRange($(this));
            });
        rangeDistance.append('<option value="0">MAX</option>');
        $([1,2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,99]).each(function(){
            rangeDistance.append('<option value="'+this+'">'+this+'м.</option>');
        });
        var rangeSelect = $("<select>").attr('class','btn-mini')
            .css({
                width: '70%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','rangeSelect')
            .change(function(){
                that.changeRange($(this));
            });
        rangeSelect.append('<option value=""></option>');
        $([1,2,3,4,5,6,7,8,9]).each(function(){
            rangeSelect.append('<option value="'+this+'">-'+(this*10)+'% за 1м сверх</option>');
        });
        $([1,2,3,4,5,6,7,8,9]).each(function(){
            var el = this;
            $([1,2,3,4,5,6,7,8,9]).each(function(){
                rangeSelect.append('<option value="'+this+el+'">'+el+' цепей на '+this+'м</option>');
            });
        });
        var rangeElement = $("<div></div>").attr('class','span2 nlm');
        rangeElement.append(rangeDistance);
        rangeElement.append(rangeSelect);
        div.append(rangeElement);
        var outEffect = $("<select>").attr('class','btn-mini')
            .css({
                width: '40%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','outEffect')
            .change(function(){
                that.changeParam($(this));
            });
        outEffect.append('<option value="0">-</option>');
        for(var k in settings.gameSettings.outEffects){
            outEffect.append('<option value="'+k.split('_')[1]+'">'+settings.gameSettings.outEffects[k].name+'</option>');
        }
        var inEffect = $("<select>").attr('class','btn-mini')
            .css({
                width: '40%',
                height: "auto"
            })
            .attr('data-num',i)
            .attr('data-param','inEffect')
            .change(function(){
                that.changeParam($(this));
            });
        inEffect.append('<option value="0">-</option>');
        for(var k in settings.gameSettings.inEffects){
            inEffect.append('<option value="'+k.split('_')[1]+'">'+settings.gameSettings.inEffects[k].name+'</option>');
        }
        var effectElement = $("<div></div>").attr('class','span2 nlm');
        effectElement.append(outEffect);
        effectElement.append(inEffect);
        effectElement.append(
            $("<input>").attr("type","button")
                .css({
                    marginLeft: 10,
                    marginTop: -10
                })
                .attr('class','btn btn-mini btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    that.data.params[$(this).data('num')] = false;
                    $(this).parent().parent().remove();
                })
        );
        div.append(effectElement);
        $("#lib_value").append(div);
    }
    this.save = function(){        
        controller.player_settings.save();
    }
    this.load = function(){

        var that = this;
        var start = 10100;
        this.clean();
        var load = function(){
            Arduino("r",start,13,false,function(data){
                    if(data[0]>10000){
                        that.data.params.push({
                            id: data[0],
                            type: data[1],
                            groupId: data[2],
                            element: data[3],
                            param: data[4],
                            value: data[5],
                            defender: data[6],
                            manna: data[7],
                            count: data[8],
                            maxCount: data[9],
                            range: data[10],
                            outEffect: data[11],
                            inEffect: data[12]
                        });
                        that.createLine(that.data.params.length-1);
                    }
                if(start<16000){
                    start+=100;
                    load();
                }else{
                    that.show();
                }
            });
        }
        load();
    }
    this.clean = function(){
        this.data.params = [];
        $("#lib_value>div").remove();
    }
    this.saveToLS = function(){
        var data = JSON.stringify(this.data.params);
        window.localStorage['lib'] = data;
    }
    this.loadFromLS = function(){
        var data = window.localStorage['lib'];
        if(!data) return;
        this.clean();
        this.data.params = $.parseJSON(data);
        for(var k in this.data.params) this.createLine(k);
    }
    var that = this;
        $('#addLibLine').click(function(){
            var i = that.data.params.length;
            var max = 10000;
            for(var i=0; i<that.data.params.length; i++) {
                if(!that.data.params[i]) continue;
                max = Math.max(max, that.data.params[i].id);
            }
            that.data.params.push({
                id: max+1,
                groupId: 0,
                param: 0,
                element: 0,
                value: 0,
                defender: 0,
                manna: 0,
                count: 0,
                maxCount: 0,
                type: 0,
                range: 0,
                outEffect: 0,
                inEffect: 0
            });
            that.createLine(i);
        });
}
$(document).ready(function(){
    controller = new Controller();
    $('a[data-toggle="tab"]').on('show', function (e) {
        var tab = e.target.href.split('#')[1];
        controller.currentTab = tab;
        controller[tab].show();
    });
    controller.settings.show();
});
    </script>
</head>
<body>
    <div class="alert alert-success" id='topAlert' style='position: absolute; margin: 0; left: 0; right: 0; top: 40px; display:none'>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <span id='alertText'></span>
    </div> 
    <div class="navbar navbar-inverse navbar-fixed-top"><div class='navbar-inner'>
        <ul class="nav">
            <li class='span3'><a class="brand" href="#"><img src="img/ruby-gear-icon.png" style="margin-right:10px"/>Кристалловед</a></li>
            <li><a href="#" class="arduinoAction" data-function="load"><img src="img/ruby-put-icon.png" style="margin-right:10px"/>Зазгрузить</a></li>
            <li><a href="#" class="arduinoAction" data-function="save"><img src="img/ruby-get-icon.png" style="margin-right:10px"/>Сохранить</a></li>
            <li><a href="#" class="arduinoAction" data-function="clean"><img src="img/ruby-delete-icon.png" style="margin-right:10px"/>Очистить</a></li>
            <!--li><a href="#" class="arduinoAction" data-function="reset"><img src="img/ruby-delete-icon.png" style="margin-right:10px"/>Стереть память</a></li-->
        </ul>
    </div></div>
    <div class="container-fluid" style='padding:0'>
        <div class="row-fluid">
            <div class="span2">
                <ul class="nav nav-pills nav-stacked"  id="baseMenu">
                    <li><a href="#init_crystall" data-toggle="tab" style="padding: 8px 5px"><img src="img/recherche-icon.png" style="margin-right:10px"/>Инициализация</a></li>
                    <li><a href="#player_settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/Knight-icon.png" style="margin-right:10px"/>Память игрока</a></li>
                    <li><a href="#weapon_settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/sword-icon.png" style="margin-right:10px"/>Память оружия</a></li>
                    <li><a href="#armor_settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/shield-icon.png" style="margin-right:10px"/>Память брони</a></li>
                    <li><a href="#crystall_settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/ruby-icon.png" style="margin-right:10px"/>Улучшения</a></li>
                    <li class="active"><a href="#settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/Settings-icon.png" style="margin-right:10px"/>Настройки</a></li>
                    <li><a href="#lib_settings" data-toggle="tab" style="padding: 8px 5px"><img src="img/book-open-icon.png" style="margin-right:10px"/>Библиотека</a></li>
                </ul>
            </div>
            <div class="span10">
                <div class="tab-content">
                    <div class="tab-pane" id="init_crystall">
                        <img src="img/recherche-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Инициализация кристалла</h1>
                        <div class='span5'><button class="btn span8 arduinoAction" data-function="initData">Инициализация</button></div>
                        <div class='span11' id="initResult"></div>
                    </div>
                    <div class="tab-pane" id="player_settings">
                        <img src="img/Knight-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Память игрока</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span12"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID пользователя</span>
                                    <span class='span2'>ID группы</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span12"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.player_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="user_id" onChange="controller.player_settings.data['userId'] = this.value*1" /></span>
                                    <span class='span2' id="playerGroupIdControll"></span>
                                    <span class='span5'><input class='span12' type="text" name="user_name" onChange="controller.player_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Параметры</legend>
                                <div class="span12"><br/>
                                    <span class='span2 nlm'>Название</span>
                                    <span class='span2 '>Значение</span>
                                    <span class='span2 '>Максимум</span>
                                    <span class='span2 '>Прирост</span>
                                    <span class='span2 '>Коэфициент (%)</span>
                                    <span class='span2 '>Устойчивость</span>
                                </div>
                                <div class="span12" id='user_params_value'></div>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="weapon_settings">
                        <img src="img/sword-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Настройка оружия</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID игры</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.weapon_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="game_id" onChange="controller.weapon_settings.data['gameId'] = this.value*1" /></span>
                                    <span class='span2'><select class='span12' type="text" name="type" onChange="controller.weapon_settings.data['type'] = this.value*1">
                                    </select></span>
                                    <span class='span5'><input class='span12' type="text" name="weapon_name" onChange="controller.weapon_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                                <br/>
                                <div class="span11"><br/>
                                    <span class='span3'>Срабатывание (порог акселерометра)</span>
                                    <span class='span3'>Задержка (между ударами в мс)</span>
                                    <span class='span2'>ID владельца</span>
                                    <span class='span2'>Урон</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span3'><input class='span12' type="text" name="level" onChange="controller.weapon_settings.data['level'] = this.value*1" /></span>
                                    <span class='span3'><input class='span12' type="text" name="delay" onChange="controller.weapon_settings.data['delay'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="owner" onChange="controller.weapon_settings.data['owner'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="damage" onChange="controller.weapon_settings.data['damage'] = this.value*1" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Воздействия</legend>
                                <div class="span12" id='weapon_value' style='margin-left:0'></div>
                                <input type='button' class='btn btn-success' id="addWeaponLine" value="+ Добавить"\>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="armor_settings">
                        <img src="img/shield-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Настройка брони</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID игры</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.armor_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="game_id" onChange="controller.armor_settings.data['gameId'] = this.value*1" /></span>
                                    <span class='span2'><select class='span12' type="text" name="type" onChange="controller.armor_settings.data['type'] = this.value*1">
                                    </select></span>
                                    <span class='span5'><input class='span12' type="text" name="armor_name" onChange="controller.armor_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                                <br/>
                                <div class="span11"><br/>
                                    <span class='span2'>ID владельца</span>
                                    <span class='span2'>Защита</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="owner" onChange="controller.armor_settings.data['owner'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="defende" onChange="controller.armor_settings.data['defend'] = this.value*1" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Воздействия</legend>
                                <div class="span12" id='armor_value' style='margin-left:0'></div>
                                <input type='button' class='btn btn-success' id="addArmorLine" value="+ Добавить"\>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="crystall_settings">
                        <img src="img/ruby-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Улучшения</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID игры</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.crystall_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="game_id" onChange="controller.crystall_settings.data['gameId'] = this.value*1" /></span>
                                    <span class='span2'><select class='span12' type="text" name="type" onChange="controller.crystall_settings.data['type'] = this.value*1"></select></span>
                                    <span class='span5'><input class='span12' type="text" name="crystall_name" onChange="controller.crystall_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Воздействия</legend>
                                <div class="span12" id='crystall_value' style='margin-left:0; margin-bottom:20px'></div>
                                <input type='button' class='btn btn-success' id="addCrystallLine" value="+ Добавить"\>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane active" id="settings">
                        <h1>Настройки</h1>
                        <form>
                            <fieldset>
                                <legend>Настройки порта</legend>
                                <div class="span11"><br/>
                                    <input class='span2' type="text" id="comport_name" placeholder="имя порта например COM5" onChange="settings.serialPort = this.value">
                                </div>
                            </fieldset>
                        <br/>
                        <br/>
                        <h1>Настройки игры</h1>
                            <fieldset id='gameSettings'>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="lib_settings">
                        <h1>Библиотека ресурсов</h1>
                        <div class="span11 nlm" style="margin-bottom:20px">
                            <button class='btn btn-mini btn-info' id='saveToLS'>Сохранить в LS</button>
                            <button class='btn btn-mini btn-info' id='loadFromLS'>Загрузить из LS</button>
                        </div>
                        <div class="span12" style='margin-left:0'>
                            <span class='span1 nlm'>ID</span>
                            <span class='span1 nlm'>Тип</span>
                            <span class='span1 nlm'>Группы</span>
                            <span class='span2 nlm'>Элемент</span>
                            <span class='span1 nlm'>Значение</span>
                            <span class='span1 nlm'>Защита</span>
                            <span class='span1 nlm'>Манна</span>
                            <span class='span1 nlm'>Зарядов</span>
                            <span class='span1 nlm'>Всего зарядов</span>
                            <span class='span2 nlm'>Дистанция   /   сверх зоны</span>
                            <span class='span1 nlm'>Эффект мага</span>
                            <span class='span1 nlm'>Эффект цели</span>
                        </div>
                        <div class="span12" id='lib_value' style='margin-left:0'></div>
                        <input type='button' class='btn btn-success' id="addLibLine" value="+ Добавить"\>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="libModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="libModalLabel" aria-hidden="true" style="width:auto">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="libModalLabel">Библиотека</h3>
        </div>
        <div class="modal-body">
            <ul class="unstyled" id="libList"></ul>
        </div>
        <div class="modal-footer">
            <button class="btn btn-success" onclick="controller.addLinesFromLib()">+ Добавить</button>
        </div>
    </div>
</body>
</html>